const WxPay = require("wechatpay-node-v3");
const fs = require("fs");
const path = require("path");
const config = require("../../config/config.default");

const cert_path = path.join(
    __dirname,
    "../../config/pay_cert/apiclient_cert.pem"
);

const cert_key_path = path.join(
    __dirname,
    "../../config/pay_cert/apiclient_key.pem"
);

// 支付信息
const pay = new WxPay({
    appid: config.wPayConfig.appid,
    mchid: config.wPayConfig.mch_id,
    publicKey: fs.readFileSync(cert_path), // 公钥
    privateKey: fs.readFileSync(cert_key_path), // 秘钥
});

// 下单接口
const placeOrders = async (ctx) => {
    // 下单请求参数
    /*
        openid:前台获取 
        total：支付金额1代表1分
        description：商品信息
        out_trade_no：商家订单号
    */
    const { openid, total, description, out_trade_no } = ctx.request.body;
    console.log(ctx.request.body, 'ctx.request.body');
    // 统一下单参数
    const params = {
        description,
        out_trade_no,
        notify_url: config.wPayConfig.notify_url,
        amount: {
            total: total,
        },
        payer: {
            openid,
        },
        scene_info: {
            payer_client_ip: "127.0.0.1",
        },   
    };
    // 微信服务器返回的支付参数
    const res = await pay.transactions_jsapi(params);    
    // 返回前端，调起支付     
    console.log(res, 'res66666');
    ctx.body = {
        code: 200,
        data: res,
        message: "下单成功",
    };
};

module.exports = {
    placeOrders,
};